<template>
    <div class="orderListRuleForm">
        <panle title='团购链接' content="团购链接"></panle>
        <div style="float: left" v-if="userInfo.popu_level == 1 && userInfo.is_popu > 1">
          <el-button class="create_link" type="primary" size="mini" @click="createdPopuLink(1)">创建一级</el-button>
          <el-button class="create_link" type="primary" size="mini" @click="createdPopuLink(2)">创建二级</el-button>
        </div>
        <!--搜索-->
        <div style="float: left">
          <el-form :inline="true" ref="form" :model="form" label-width="100px" class="demo-form-inline">
            <el-form-item label="唯一识别码:" prop="link_yard">
              <el-input size="mini" placeholder="请输入" v-model="form.link_yard"></el-input>
            </el-form-item>
            <el-form-item label="商品名称:" prop="goods_name">
              <el-input size="mini" placeholder="请输入" v-model="form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="状态:" prop="link_status">
              <el-select v-model="form.link_status" placeholder="请选择" size="mini">
                <el-option label="上架" value="1"></el-option>
                <el-option label="下架" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search" size="mini">搜索</el-button>
              <el-button @click="resetForm('form')" size="mini">重置</el-button>
              <el-button size="mini" @click="init()">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--列表-->
        <div class="table-wrap">
          <el-table :data="tableData" v-loading="loading" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all>
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="name" label="商品名称"></el-table-column>
            <el-table-column prop="img" label="缩略图">
              <template slot-scope="scope">
                <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="link_yard" label="唯一识别码"></el-table-column>
            <el-table-column prop="group_spec" label="商品规格/价格（单位元）/佣金（单位元）" width="200">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.spec" :key="index" style="margin-bottom: 10px !important;">
                  {{item.name}}/{{item.price}}/{{item.link_divide_price}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="group_hour" label="成团时间（小时）"></el-table-column>
            <el-table-column prop="group_date_time" label="活动时间"></el-table-column>
            <el-table-column prop="people_num" label="成团人数限制"></el-table-column>
            <el-table-column prop="link_level" label="级别">
              <template slot-scope="scope">
                <span v-if="scope.row.link_level == 1">一级</span>
                <span v-else>二级</span>
              </template>
            </el-table-column>
            <el-table-column prop="link_status" label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.link_status == 1">上架</span>
                <span v-else>下架</span>
              </template>
            </el-table-column>
              <el-table-column prop="content" label="当前海报" width="145">
                  <template slot-scope="scope">
                      <el-image v-if="scope.row.content" :src="scope.row.content" fit="fill" style="width: 120px;"></el-image>
                      <p v-else>未设置</p>
                  </template>
              </el-table-column>
            <el-table-column prop="user_name" label="创建人"></el-table-column>
            <el-table-column prop="add_time" label="创建时间"></el-table-column>
            <el-table-column prop="link_url" label="团购链接"></el-table-column>
            <el-table-column prop="id" label="操作">
              <template slot-scope="scope">
                <el-button v-if="userInfo.popu_level == 1 && userInfo.is_popu > 1" type="text" size="mini" icon="fa  fa-pencil" @click="checkPopu(scope.row)">查看</el-button>
                <el-button v-if="userInfo.popu_level == 1 || userInfo.is_popu == 1" type="text" size="mini" icon="fa  fa-pencil" @click="editPopu(scope.row)">编辑</el-button>
                <el-button v-if="userInfo.popu_level == 1 || userInfo.is_popu == 1" type="text" size="mini" icon="fa  fa-pencil" @click="toggleStatus(scope.row)">
                  <span v-if="scope.row.link_status == 1">关闭</span>
                  <span v-else>开启</span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handlePopuSizeChange" @current-change="handlePopuCurrentChange"
                           :current-page="form.pagePopuNumber" :page-sizes="[10, 50, 100, 200]"
                           :page-size="form.pagePopuSize"
                           background layout="total, sizes, prev, pager, next, jumper"
                           :total="form.popuTotal">
            </el-pagination>
          </div>
        </div>
        <!--创建/修改-->
        <el-dialog :visible.sync="groupOpen" :before-close="handleClose" width="1000px" append-to-body :title="!resForm.id ? '创建团购链接' : '修改团购链接'">
            <el-form ref="resForm" :model="resForm">
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="添加商品：" prop="goods_id">
                            <el-button type="primary" size="mini" v-if="!resForm.id" @click="selectGoods">添加商品</el-button>
                        </el-form-item>
                        <el-table :data="currentGoods" style="width: 100%;margin-bottom: 20px;" border stripe default-expand-all v-if="currentGoodsShow == true && !resForm.id">
                            <el-table-column prop="name" label="商品名称"></el-table-column>
                            <el-table-column prop="desc" label="商品描述"></el-table-column>
                            <el-table-column prop="img" label="缩略图">
                                <template slot-scope="scope">
                                    <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
                                </template>
                            </el-table-column>
                            <el-table-column prop="type" label="类型">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.type == 1">实体</span>
                                    <span v-else>虚拟</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="spec" label="规格(名称/价格（元）/佣金（元）)">
                              <template slot-scope="scope">
                                <el-tag v-for="(item,index) in scope.row.spec" :key="index" style="margin-bottom: 10px !important;">
                                  {{item.name}}/{{item.price}}/{{item.goods_commission}}
                                </el-tag>
                              </template>
                            </el-table-column>
                        </el-table>
                        <el-table :data="checkGroupData.goods_data" v-if="resForm.id" style="width: 100%;margin-bottom: 20px;" border stripe default-expand-all>
                            <el-table-column prop="name" label="商品名称"></el-table-column>
                            <el-table-column prop="desc" label="商品描述"></el-table-column>
                            <el-table-column prop="img" label="缩略图">
                                <template slot-scope="scope">
                                    <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
                                </template>
                            </el-table-column>
                            <el-table-column prop="type" label="类型">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.type == 1">实体</span>
                                    <span v-else>虚拟</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                    <el-col :span="14">
                      <el-form-item label="成团人数（单位：人）：" prop="people_num">
                        <el-input-number size="mini" :min="2" label="成团人数不得低于2人" v-model="resForm.people_num"></el-input-number>
                      </el-form-item>
                    </el-col>
                    <el-col :span="14">
                      <el-form-item label="成团时间（单位：小时）：" prop="group_hour">
                        <el-input-number size="mini" :min="1" label="成团时间不得低于1小时" v-model="resForm.group_hour"></el-input-number>
                      </el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item label="开团开始和结束时间:" prop="group_apply_time">
                        <el-date-picker
                            v-model="resForm.group_apply_time"
                            type="datetimerange"
                            align="right"
                            size="mini"
                            unlink-panels
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="pickerOptions"
                            :default-time="['00:00:00', '23:59:59']">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设置分佣：" prop="link_divide_price">
                          <el-table :data="resForm.goods_spec" style="width: 100%">
                            <el-table-column prop="name" label="规格名称" width="180"></el-table-column>
                            <el-table-column prop="price" label="商品价格（单位元）" width="180"></el-table-column>
                            <el-table-column prop="goods_commission" label="商品总佣金（单位元）" width="180"></el-table-column>
                            <el-table-column prop="commission" label="设置佣金（单位元）">
                              <template slot-scope="scope">
                                <el-input class="w60" :max="scope.row.commission" @input="handleInput(scope.row.commission, $event)" size="mini" v-model="scope.row.commission"></el-input>
                              </template>
                            </el-table-column>
                            <el-table-column prop="limit_num" label="限购次数">
                              <template slot-scope="scope">
                                <el-input-number :min="0" size="mini" v-model="scope.row.limit_num" placeholder="0"></el-input-number>
                              </template>
                            </el-table-column>
                          </el-table>


<!--                          <div v-for="(item,index) in resForm.goods_spec" :key="index">-->
<!--                              <div>-->
<!--                                <el-form-item :label="item.name">-->
<!--                                  <span>佣金</span>-->
<!--                                  <el-input class="w60" :max="item.commission" @input="handleInput(item.commission, $event,index)" size="mini" v-model="item.commission"></el-input>-->
<!--                                </el-form-item>-->
<!--                              </div>-->
<!--                          </div>-->
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-dialog :visible.sync="goodsOpen" width="1000px" append-to-body title="选择商品">
                <el-form :inline="true" ref="goodsForm" :model="goodsForm" label-width="100px" class="demo-form-inline">
                    <el-form-item label="商品名称:" prop="goods_name">
                        <el-input size="mini" placeholder="请输入" v-model="goodsForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="search" size="mini">搜索</el-button>
                    </el-form-item>
                </el-form>
                <div class="table-wrap">
                    <el-table :data="tableGoodsData" v-loading="loading" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all>
                        <el-table-column prop="name" label="商品名称"></el-table-column>
                        <el-table-column prop="img" label="缩略图">
                            <template slot-scope="scope">
                                <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="类型">
                            <template slot-scope="scope">
                                <span v-if="scope.row.type == 1">实体</span>
                                <span v-else>虚拟</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="desc" label="商品描述"></el-table-column>
                        <el-table-column prop="spec" label="规格(名称/价格（元）/佣金（元）)">
                          <template slot-scope="scope">
                            <el-tag v-for="(item,index) in scope.row.spec" :key="index" style="margin-bottom: 10px !important;">
                              {{item.name}}/{{item.price}}/{{item.commission}}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态">
                            <template slot-scope="scope">
                                <span v-if="scope.row.status == 1">上架</span>
                                <span v-else>下架</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="id" label="操作">
                            <template slot-scope="scope">
                                <el-button v-if="selectGoodsItem.id != scope.row.id" type="text" size="mini" icon="fa fa-pencil" @click="selectGoodsData(scope.row)">添加商品</el-button>
                                <el-button v-if="selectGoodsItem.id == scope.row.id" type="text" size="mini" icon="fa fa-pencil" @click="cancelSlect(scope.row)">取消选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="block">
                        <el-pagination @size-change="handleGoodsSizeChange" @current-change="handleGoodsCurrentChange"
                                       :current-page="goodsForm.pageGoodsNumber" :page-sizes="[10, 50, 100, 200]"
                                       :page-size="goodsForm.pageGoodsSize"
                                       background layout="total, sizes, prev, pager, next, jumper"
                                       :total="goodsForm.goodsTotal">
                        </el-pagination>
                    </div>
                </div>
            </el-dialog>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleClose" size="small">取 消</el-button>
                <el-button type="primary" @click="!resForm.id ? submitForm('resForm') : subEditForm('resForm') " size="small">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="checkGroupOpen" :before-close="handleClose" v-loading="loading" width="500px" append-to-body title="查看团购链接二维码">
            <div v-if="checkGroupData.is_popu != 1" style="display: flex;align-items: center;justify-content: center; height: 300px;">
              <el-image :src="checkGroupData.popu_link_qrcode" fit="fill" style="width: 300px;height: 300px;"></el-image>
            </div>
            <el-button style="margin-left: 15px" type="text" size="mini" @click="downloadQrcode(checkGroupData.popu_link_qrcode)">下载</el-button>
        </el-dialog>
    </div>
</template>

<script>
import {
  checkGroupLink,
  createGroupLink,
  editeGroupLink,
  editeLinkStatus,
  getGoodsList,
  getList,
  getLoginInfo,
  viewGroupLink
} from "@/api/sell/grouplink/grouplink";

import Panle from '@/components/Panle';
import PersButton from '@/components/PersButton';
import {hasPermission, isShow} from '@/common/permission';

export default {
    name:'Group-Link',
    components: {
        Panle,
        PersButton,
    },

    data() {
        return {
            groupOpen: false, //创建/编辑弹框是否显示
            goodsOpen:false,//选择商品弹框是否显示
            loading:false,//加载
            currentGoodsShow:false,
            checkGroupOpen:false,
            tableData: [], //推广链接列表
            tableGoodsData: [], //商品列表
            selectGoodsItem:[], //选中的商品
            currentGoods:[],//选中的商品信息
            checkGroupData:[], //查看团购链接的数据
            replenishOpen:false, //补货是否显示
            radio: '1',
            created_level:1,
            form: {
                link_yard:'',
                goods_name:'',
                link_status:'',
                pagePopuSize: 10,
                pagePopuNumber: 1,
                popuTotal: 0,

            },
            goodsForm:{
                goods_name:'',
                pageGoodsSize: 10,
                pageGoodsNumber: 1,
                goodsTotal: 0,
            },
            resForm: {
                id:'',
                people_num:2,
                group_hour:1,
                group_apply_time:[],
                goods_spec:[],
            },

            userInfo:{},
            pickerOptions: {
              disabledDate(v) {
                return v.getTime() < new Date().getTime() - 86400000;//  - 86400000是否包括当天
              }
            },

          default_num:0
        }
    },
    created() {
        this.init();
    },
    methods: {
      hasPermission,
      isShow,
      init() {
        this.loading = true;
        getList(this.form).then((res) => {
          this.tableData = res.data.data;
          this.form.popuTotal = res.data.total;
          this.loading = false;
        });
        getLoginInfo().then((res) => {
          this.userInfo = res.data;
          this.loading = false;
        })
      },
      //添加或者编辑完成后初始化弹框的内容
      initGroup() {
        this.selectGoodsItem = [];
        this.currentGoods = [];
        this.currentGoodsShow = false;
        this.radio = '1';
        this.resForm.id = '';
        this.resForm.group_apply_time = [];
        this.resForm.goods_spec = [];
      },

      handleInput(c, n) {
        if(n > c){
          this.msgSuccess('一级佣金不能超过总佣金');
        }
      },

      //关闭弹框回调
      handleClose() {
        this.groupOpen = false;
        this.checkGroupOpen = false;
        this.created_level = 1;
        this.initGroup();
      },

      search: function () {
        this.loading = true;
        this.form.pagePopuSize = 10;
        this.form.pagePopuNumber = 1;
        this.init();
      },
      handlePopuSizeChange: function (e) {
        this.form.pagePopuSize = e;
        this.init();
      },
      handlePopuCurrentChange: function (e) {
        this.form.pagePopuNumber = e;
        this.init();
      },
      handleGoodsSizeChange: function (e) {
        this.goodsForm.pageGoodsSize = e;
        this.init();
      },
      handleGoodsCurrentChange: function (e) {
        this.goodsForm.pageGoodsNumber = e;
        this.init();
      },
      resetForm(formName) {
        this.form.link_yard = ''
        this.form.goods_name = ''
        this.form.link_status = ''
        this.init();
      },
      //创建提交
      submitForm: function (data) {
        this.$refs[data].validate((valid) => {
          if (valid) {
            this.resForm.goods_id = this.selectGoodsItem.id;
            this.resForm.created_level = this.created_level;
            createGroupLink(this.resForm).then((res) => {
              if (res.code == 200) {
                this.msgSuccess(res.msg);
                this.groupOpen = false;
                this.init();
                this.initGroup();
              } else {
                this.msgError(res.msg);
              }
            })
          } else {
            return false;
          }
        })
      },

      //编辑提交
      subEditForm: function (data) {
        this.$refs[data].validate((valid) => {
          if (valid) {
            editeGroupLink(this.resForm).then((res) => {
              if (res.code == 200) {
                this.msgSuccess(res.msg);
                this.groupOpen = false;
                this.init();
                this.initGroup();
              } else {
                this.msgError(res.msg);
              }
            })
          } else {
            return false;
          }
        })
      },

      //创建推广链接
      createdPopuLink: function (e) {
        this.groupOpen = true;
        this.created_level = e;
      },
      //添加商品
      selectGoods: function (e) {
        this.goodsOpen = true;
        this.loading = true;
        getGoodsList(this.goodsForm).then((res) => {
          this.tableGoodsData = res.data.data;
          this.goodsForm.goodsTotal = res.data.total;
          this.loading = false;
        })
      },

      //选择商品
      selectGoodsData: function (e) {
        this.selectGoodsItem = e;
        this.currentGoods = [e];
        e.spec.forEach(function (item, index) {
          e.spec[index].goods_commission = item.commission
        })
        this.resForm.goods_spec = e.spec;
        this.goodsOpen = false;
        this.currentGoodsShow = true;
      },
      //取消选择
      cancelSlect: function (e) {
        this.selectGoodsItem = [];
        this.currentGoodsShow = false;
        this.goodsOpen = false;
      },
      //查看链接
      checkPopu: function (e) {
        this.loading = true;
        var param = {
          'id': e.id
        }
        checkGroupLink(param).then((res) => {
          if (res.code == 200) {
            this.checkGroupOpen = true;
            this.checkGroupData = res.data;
            this.currentGoods = res.data.goods_data;
            this.loading = false;
          }
        }).catch((err) => {
          this.loading = false;
        })
      },
      //复制链接
      copyText: async function (e) {
        await navigator.clipboard.writeText(e);
        this.msgSuccess("复制成功！");
      },
      //base64 to png
      convertBase64ToPng(base64Data, callback) {
        // 将base64字符串转换为Blob对象
        const byteCharacters = atob(base64Data.split(',')[1]);
        const mimeString = base64Data.split(',')[0].match(/:([^;]+);/)[1];
        const arrayBuffer = new ArrayBuffer(byteCharacters.length);
        const uintArray = new Uint8Array(arrayBuffer);
        for (let i = 0; i < byteCharacters.length; i++) {
          uintArray[i] = byteCharacters.charCodeAt(i);
        }
        const blob = new Blob([uintArray], {type: mimeString});
        callback(blob);
      },
      //下载二维码
      downloadQrcode: function (e) {
        this.convertBase64ToPng(e, pngData => {
          var downloadLink = document.createElement('a');
          downloadLink.href = URL.createObjectURL(pngData);
          downloadLink.download = 'popu_link_qrcode.png';
          downloadLink.click();
        })
      },
      //编辑链接的数据
      editPopu: function (e) {
        this.loading = true;
        this.resForm.id = e.id;
        var param = {
          'id': e.id
        }
        viewGroupLink(param).then((res) => {
          if (res.code == 200) {
            this.groupOpen = true;
            this.checkGroupData = res.data;
            this.resForm.group_apply_time = res.data.group_apply_time;
            this.resForm.goods_id = res.data.goods_id;
            this.resForm.goods_spec = res.data.spec
            this.loading = false;
          }
        })
      },
      //改变状态
      toggleStatus: function (e) {
        var params = {
          "id": e.id,
          'link_status': e.link_status == 1 ? 0 : 1,
        }
        editeLinkStatus(params).then((res) => {
          if (res.code == 200) {
            this.msgSuccess(res.msg);
            this.init();
          } else {
            this.msgError(res.msg);
          }
        })
      },
    }
}

</script>

<style lang="scss" scoped>
.demo-form-inline {
    margin: 20px;

    .el-form-item {
        margin-bottom: 0;
    }
}
.el-form--inline .el-form-item {
    display: inline-block;
    vertical-align: top;
}

.orderListRuleForm .el-form-item {
    margin-bottom: 0;
}

.search-content {
    width: 100%;
    margin: 20px;
}

.create_link{
    margin-top: 7px;
    margin-left: 10px;
    float: left;
}

.w50{
    width: 50px !important;
}
.w60{
    width: 60px !important;
}
.mr20{
    margin-right: 20px;
}
</style>
